import { FC, SetStateAction, useEffect, useRef, useState } from 'react'
import './style.less'
import { Cascader, Flex, Menu, Modal } from 'antd'
import { DownloadOutlined } from '@ant-design/icons'
import { getMapTree } from '@hs-admin/api'
import loadIndented from './useIndented'
import { HsAdminSpin } from '@hs-admin/base-components'
import useRight from './Right'
import { useLocation, useSearchParams, useNavigate } from 'react-router-dom'
import { getPublishPlatformMap } from '@/hooks/usePublishMap'
import { addTrackMonitors, deleteTrackMonitors, getMonitorsTrackList } from '@/api/monitors'
import { getItem, message, removeItem, setItem } from '@hs-admin/utils'
import { useTypeStore } from '@/store/useMonitors'
import { MyIcon } from '@/components/MyIcon'
import ReightList from './components/Industry_data'
import CapitalTrends from './CapitalTrends/index'
import { getAllPlatform, getAllPublishDataItem } from '@hs-server/api'
import { AreaTreeSelect } from '@hs-server/components'
interface Props {
  from:
    | '生物医药专区'
    | '新能源专区'
    | '汽车专区'
    | '新材料专区'
    | '未来产业专区'
    | '数字经济专区'
    | '高端装备专区'
    | '农业专区'
    | '食品专区'
    | '传统制造业专区'
    | '数字创意专区'
}

const BiomedicalArea: FC<Props> = (props: Props) => {
  const { from } = props
  const [searchParams] = useSearchParams()
  const [leftTabItems, setleftTabItems] = useState<any[]>([])
  const [selectedKeys, setselectedKeys] = useState<string[]>([])
  const [OpenKeys, setOpenKeys] = useState<string[]>([])
  const [loading, setloading] = useState(true)
  const [BreadcrumbList, setBreadcrumbList] = useState<any[]>([])
  const location = useLocation()
  const navigate = useNavigate()
  const antvInstance = useRef<any>({})
  const [selectNodeItem, setselectNodeItem] = useState<any>({})
  const [release_item_id, SetRelease_item_id] = useState('')
  const [release_item_name, SetRelease_item_name] = useState('')
  const graph_code = useRef('')
  const mapData: any = useRef({})
  const monitorsRegion = useRef<any[]>([])
  const [currentNodeMonitorsStatus, setCurrentNodeMonitorsStatus] = useState<any>({})
  const setUpdateTrack = useTypeStore((state) => state.setUpdateTrack)
  //展示右边的产业链图谱
  const [RightShow, setRightShow] = useState('产业链图谱')
  //选择的赛道
  const [activeTrackRow, setactiveTrackRow]: any = useState([])
  const [open, setOpen] = useState(false)
  const [publishTrackList, setpublishTrackList] = useState<any[]>([])
  const [regionValue, setregionValue] = useState(null)
  const regionCode = useRef(null)

  const [industryName, setindustryName] = useState('')

  const { Right, updateAreaSearch, updateHsIndSearch } = useRight({
    BreadcrumbList
  })

  const getNodeData = (_nodeIdValue: string | null, item: any) => {
    if (item) {
      const { model } = item
      setBreadcrumbList((prev) => {
        prev = model.parent
          ? model.parent
              .map((ele: any) => ({
                title: ele.get('parent')?.node_name,
                depth: ele.get('parent')?.depth + 1,
                id: ele.get('parent')?.id
              }))
              .concat([{ title: model?.node_name, depth: model?.depth + 1, id: model?.id }])
          : [{ title: model?.node_name, depth: model?.depth + 1, id: model?.id }]
        return [...prev]
      })
      updateHsIndSearch([
        {
          code_depth: model?.depth + 1,
          graph_code: `${graph_code.current}`,
          ind_code: item.id,
          show: model?.node_name
        }
      ])

      getMonitorsTrackList({}).then((res) => {
        const hasItem = res.items.find((ele: { node_id: any }) => ele.node_id === model.id)
        if (hasItem) {
          const areaList = hasItem.region.split('-').map((item: string) => item.split('|'))
          if ((regionCode.current && hasItem.region && areaList.at(-1).includes(regionCode.current)) || (!regionCode.current && !hasItem.region)) {
            setCurrentNodeMonitorsStatus({ ...model, ismonitor: true, mid: hasItem.id })
          } else {
            setCurrentNodeMonitorsStatus({ ...model, ismonitor: false })
          }
        } else {
          setCurrentNodeMonitorsStatus({ ...model, ismonitor: false })
        }
      })
    } else {
      setBreadcrumbList((prev) => {
        prev = [
          {
            title: mapData.current.node_name,
            depth: mapData.current.depth + 1,
            id: mapData.current.id
          }
        ]
        return [...prev]
      })
      updateHsIndSearch([
        {
          code_depth: 1,
          graph_code: `${graph_code.current}`,
          ind_code: mapData.current.id,
          show: mapData.current.node_name
        }
      ])
    }
  }
  const reLoadChart = () => {
    antvInstance.current = loadIndented('brainContainer', mapData.current, getNodeData)
  }
  const initMap = () => {
    antvInstance.current = loadIndented('brainContainer', mapData.current, getNodeData)
    window.addEventListener('resize', reLoadChart)
  }
  const selectedTree = (selectItem: { key: string; label: SetStateAction<string>; map_id: string; name: string; leval: number }) => {
    if (selectItem) {
      if (selectItem.map_id) {
        getMapTree({ id: selectItem.map_id }).then((res: any) => {
          const formatData = (data: any, parent?: any) => {
            data.label = data.node_name || ''
            data.id = data.node_code
            if (parent) {
              data.parent ||= [new Map([['parent', parent]])]
              if (parent.parent?.length) {
                data.parent = [...parent.parent, new Map([['parent', parent]])]
              }
            }
            data.children?.forEach((item: any) => {
              formatData(item, data)
            })
          }

          mapData.current = res.length ? res[0] : {}
          formatData(mapData.current, null)
          initMap()
          setBreadcrumbList([{ title: mapData.current.label, id: mapData.current.id, depth: 1 }])
          setloading(false)
        })
      }
      setselectedKeys([selectItem.key])
      setselectNodeItem(selectItem)
      graph_code.current = selectItem.map_id
    }
  }

  const getMapChildren = (treeList: any[]) => {
    treeList.forEach(async (item: { map_id: any; children: any[]; node_name: string; node_code: string }) => {
      await getMapTree({ id: item.map_id }).then((res: any) => {
        if (res.length) {
          item.node_name = res[0].node_name
          item.node_code = res[0].node_code
        }
      })
    })
  }

  const handlePublishMapData = (unique: any[]) => {
    const treeList = unique.map((first: any) => ({
      label: first.node_name,
      value: first.id,
      industry_domain: first.industry_domain,
      map_id: first.map_id
    }))
    return treeList
  }

  function updateURLParams(pathname: any, activeId: any, mapId: any, name: any) {
    const url = `${pathname}?activeId=${activeId}&from=${encodeURIComponent(name)}&map_id=${mapId}`
    navigate(url)
  }

  useEffect(() => {
    setloading(true)
    getPublishPlatformMap(from).then((unique) => {
      let fielabel: string = '细分领域'
      let fiekey: string = ''
      let Paramsitem: any = {}
      if (searchParams.get('from')) {
        fielabel = searchParams.get('from') ?? '细分领域'
        setindustryName(fielabel)
      }
      if (searchParams.get('activeId')) {
        fiekey = searchParams.get('activeId') ?? ''
        Paramsitem = {
          key: unique.filter((item: any) => (item.id === fiekey ? item.id : null))[0]?.id,
          industry_domain: unique.filter((item: any) => (item.id === fiekey ? item.id : null))[0]?.industry_domain,
          map_id: unique.filter((item: any) => (item.id === fiekey ? item.id : null))[0]?.map_id
        }
      }
      const treeList: any[] = [
        {
          label: '产业链图谱',
          id: '产业链图谱',
          name: fielabel,
          icon: <MyIcon type="icon-chanyeliantupu" />,
          key: Paramsitem.key,
          leval: 1,
          industry_domain: Paramsitem.industry_domain,
          map_id: Paramsitem.map_id
        },
        {
          label: '供应链图谱',
          id: '供应链图谱',
          disabled: true,
          name: fielabel,
          icon: <MyIcon type="icon-gongyingliantupu" />,
          key: '供应链图谱'
        },
        {
          label: '资本数据',
          id: '资本数据',
          name: fielabel,
          icon: <MyIcon type="icon-zibenqushi" />,
          key: '资本数据'
        },
        // // 第一版上线，没数据，暂时隐藏。 勿删！！！！！！
        // {
        //   label: '市场数据',
        //   id: '市场数据',
        //   name: fielabel,
        //   icon: <MyIcon type="icon-shichangqushi" />,
        //   key: '市场数据'
        // },
        {
          label: '行业数据',
          id: '行业数据',
          name: fielabel,
          icon: <MyIcon type="icon-hangyeshuju" />,
          key: '行业数据',
          children: []
        }
      ]
      setleftTabItems(treeList)
      if (treeList.length) {
        setOpenKeys([treeList[0].key])
        setselectedKeys([treeList[0].key])
        let selectItem: any = {}
        if (searchParams.get('activeId')) {
          selectItem = treeList[0]?.key === searchParams.get('activeId') ? treeList[0] : treeList
        } else {
          selectItem = treeList
        }
        selectedTree(selectItem)
      } else {
        antvInstance.current.clear?.()
        setloading(false)
      }
      platformsList(from, treeList)
    })

    setRightShow('产业链图谱')
  }, [location])

  const platformsList = async (ZoneName: string, treeList: any[]) => {
    const data = await getAllPlatform({ use_for: 'data_item' })
    const froms = `产业预警通-${ZoneName}`
    const dataList = data.filter((item: any) => item.label === '产业预警通')
    const childrenList = dataList[0].children.filter((item: any) => item.label === froms)
    const arr = childrenList[0].children
      ? childrenList[0].children.map((its: any) => ({
          key: its.value,
          label: its.label,
          id: '行业数据',
          children: []
        }))
      : []
    if (!arr.length) {
      const _index = treeList.findIndex((item) => item.id === '行业数据')
      treeList.splice(_index, 1)
    }

    const allAreaList: any[] = []

    arr.forEach((element: any) => allAreaList.push(getAllPublishDataItems(element.key, element)))

    let _activeItem: any = []

    const activeName = getItem('activeName')

    SetRelease_item_name(activeName)

    Promise.all(allAreaList).then((_res: any) => {
      setleftTabItems(() => {
        treeList.map((item: any) => {
          if (item.id === '行业数据') {
            item.children = arr
          }
          if (activeName && item.label === activeName) {
            setRightShow(item.id)
            setOpenKeys([item.id])
            _activeItem = [item.key]
          }
        })
        return [...treeList]
      })
      arr?.map((ite: any) => {
        ite.children.map((it: any) => {
          if (activeName && it.label === activeName) {
            setRightShow(it.id)
            setOpenKeys([it.id])
            _activeItem = [it.key]
            SetRelease_item_id(it.key.split('|')?.[0])
          }
        })
      })
      if (_activeItem.length) setselectedKeys(_activeItem)
    })
  }

  //给左侧菜单添加title属性 有悬浮效果
  const setMenuContentTitle = () => {
    const doms = document.querySelectorAll('.left-tabs .ant-menu .ant-menu-submenu .ant-menu .ant-menu-item .ant-menu-title-content')
    doms.forEach((item: any) => item.setAttribute('title', item.innerText))
  }

  const getAllPublishDataItems = (key: any, row: any) => {
    return new Promise((resolve) => {
      getAllPublishDataItem({ platform_id__in: key, page_size: 199 }).then((res: any) => {
        row.children = res.map((its: any) => ({
          key: `${its.value}|${Math.random()}`,
          label: its.label,
          id: '行业数据',
          icon: <MyIcon type="icon-dian" />
        }))
        resolve(res)
      })
    })
  }
  // 校验监测状态
  const checkMonitorsStatus = (value: any) => {
    getMonitorsTrackList({}).then((res) => {
      const nodeItem = BreadcrumbList.at(-1)
      const hasItem = res.items.find((ele: { node_id: any }) => ele.node_id === nodeItem.id)
      if (hasItem) {
        const areaList = hasItem.region.split('-').map((item: string) => item.split('|'))
        if ((value && hasItem.region && areaList.at(-1).includes(value)) || (!value && !hasItem.region)) {
          setCurrentNodeMonitorsStatus({ ...nodeItem, ismonitor: true, mid: hasItem.id })
        } else {
          setCurrentNodeMonitorsStatus({})
        }
      }
    })
  }

  useEffect(() => {
    const p1 = getPublishPlatformMap('生物医药专区').then((unique) => {
      const treeList = handlePublishMapData(unique)
      getMapChildren(treeList)
      return treeList
    })
    const p2 = getPublishPlatformMap('新能源专区').then((unique) => {
      const treeList = handlePublishMapData(unique)
      getMapChildren(treeList)
      return treeList
    })
    const p3 = getPublishPlatformMap('汽车专区').then((unique) => {
      const treeList = handlePublishMapData(unique)
      getMapChildren(treeList)
      return treeList
    })
    const p4 = getPublishPlatformMap('新材料专区').then((unique) => {
      const treeList = handlePublishMapData(unique)
      getMapChildren(treeList)
      return treeList
    })
    Promise.allSettled([p1, p2, p3, p4]).then((res: any[]) => {
      setpublishTrackList([
        {
          label: '生物医药产业',
          value: '生物医药产业',
          children: res[0].value
        },
        {
          label: '新能源产业',
          value: '新能源产业',
          children: res[1].value
        },
        {
          label: '汽车产业',
          value: '汽车产业',
          children: res[2].value
        },
        {
          label: '新材料产业',
          value: '新材料产业',
          children: res[3].value
        }
      ])
    })
  }, [])

  return (
    <div className="biomedical-area-page-wrapper">
      {loading && <HsAdminSpin />}
      <div className="left-tabs-title flex justify-between items-center">
        <div className="max-w-160px" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {industryName}
        </div>
        <div className="text-blue" style={{ cursor: 'pointer', fontSize: '14px' }} onClick={() => setOpen(true)}>
          换赛道
        </div>
      </div>
      <Flex gap="large">
        <Menu
          className="left-tabs overflow-auto"
          mode="inline"
          openKeys={OpenKeys}
          selectedKeys={selectedKeys}
          items={leftTabItems}
          onClick={({ domEvent, key }) => {
            setItem('activeName', domEvent.target.innerText)
            let selectItem: any = {}
            leftTabItems?.forEach((item: any) => {
              if (item.key === key) {
                selectItem = item
              } else {
                item.children?.forEach((element: any) => {
                  element.children?.forEach((its: any) => {
                    if (its.key === key) selectItem = its
                  })
                })
              }
            })
            selectedTree(selectItem)

            SetRelease_item_name(selectItem.label)

            SetRelease_item_id(key.split('|')?.[0])
          }}
          onSelect={(e: any) => {
            setRightShow(e.item.props.id)
          }}
          onOpenChange={(openKeys: string[]) => {
            setTimeout(() => setMenuContentTitle(), 100)
            setOpenKeys(openKeys)
          }}
        />
        {RightShow === '产业链图谱' && (
          <>
            <div className="center-box mt--40px">
              <Flex align="center" gap={'middle'} className="my-2">
                <h1 className="module-title">{selectNodeItem.name}</h1>
                <p>区域选择：</p>
                <AreaTreeSelect
                  value={regionValue}
                  onChange={(value: any, label: string) => {
                    const arr: any = []
                    if (value) {
                      const obj: any = {
                        value,
                        show: label[0]
                      }
                      arr.push(obj)
                    }
                    updateAreaSearch(arr)
                    checkMonitorsStatus(value)
                    setregionValue(value)
                    regionCode.current = value
                  }}
                  onSelect={(_value: any, node: { parent: any; label: any; value: any }) => {
                    if (node.parent) {
                      monitorsRegion.current = [...node.parent, { label: node.label, value: node.value }]
                    } else {
                      monitorsRegion.current = [{ label: node.label, value: node.value }]
                    }
                  }}
                  placeholder="请选择区域"
                  className="w-90"
                />
              </Flex>
              <div className="map-box" id="brainContainer"></div>
            </div>
            <div className="right-wrapper">
              <Flex align="center" gap={'middle'} className="mt--34px">
                {!currentNodeMonitorsStatus.ismonitor && (
                  <div
                    className="flex items-center text-#0779FF rounded-3xl border-1 border-#0779FF py-4px px-16px cursor-pointer"
                    onClick={() => {
                      const nodeItem = BreadcrumbList.at(-1)
                      const params = {
                        map_id: `${graph_code.current}`,
                        map_name: selectNodeItem.name,
                        node_id: nodeItem.id,
                        node_level: nodeItem.depth,
                        node_name: nodeItem.title,
                        region: monitorsRegion.current.length
                          ? monitorsRegion.current.map((item: { label: any; value: any }) => `${item.label}|${item.value}`).join('-')
                          : '',
                        released_map_id: selectNodeItem.key
                      }
                      addTrackMonitors(params).then(() => {
                        message.success('监测成功，在监测模块查看')
                        getMonitorsTrackList({}).then((res) => {
                          const hasItem = res.items.find((ele: { node_id: any }) => ele.node_id === nodeItem.id)
                          if (hasItem) {
                            setCurrentNodeMonitorsStatus({ ...nodeItem, ismonitor: true, mid: hasItem.id })
                          }
                        })
                        setUpdateTrack(true)
                      })
                    }}>
                    <img src="/static/img/BiomedicalArea/add-watch.png" alt="" className="w-12px mr-2" />
                    添加监测
                  </div>
                )}
                {currentNodeMonitorsStatus.ismonitor && (
                  <div
                    className="flex items-center text-#0779FF rounded-3xl border-1 border-#0779FF py-4px px-16px cursor-pointer"
                    onClick={() => {
                      deleteTrackMonitors({ id: currentNodeMonitorsStatus.mid }).then(() => {
                        message.success('已取消监测')
                        setCurrentNodeMonitorsStatus({})
                        setUpdateTrack(true)
                      })
                    }}>
                    - 取消监测
                  </div>
                )}
                <div className="flex items-center text-#00000040 rounded-3xl border-1 border-#00000040 py-4px px-16px download-disabled">
                  <DownloadOutlined className="w-12px mr-2" />
                  下载报告
                </div>
              </Flex>
              {Right}
            </div>
          </>
        )}
        {RightShow === '行业数据' && (
          <div className="Industry_data pr-30px mt--40px">
            <Flex align="center" gap={'middle'} className="my-2">
              <ReightList release_item_id={release_item_id} release_item_name={release_item_name} />
            </Flex>
          </div>
        )}
        {RightShow === '资本数据' && (
          <>
            <CapitalTrends type="capital"></CapitalTrends>
          </>
        )}
        {/* 第一版上线，没数据，暂时隐藏。 勿删！！！！！！ */}
        {/* {RightShow === '市场数据' && (
          <>
            <CapitalTrends type="market"></CapitalTrends>
          </>
        )} */}
      </Flex>
      <Modal
        title="赛道监测"
        open={open}
        width="20vw"
        onCancel={() => {
          setactiveTrackRow([])
          setOpen(false)
        }}
        onOk={() => {
          if (activeTrackRow?.length) {
            setindustryName(activeTrackRow[1].label)

            selectedTree(activeTrackRow[1])

            setselectedKeys([leftTabItems[0].key])

            setRightShow('产业链图谱')

            setselectNodeItem({ ...activeTrackRow[1], name: activeTrackRow[1].label })

            platformsList(activeTrackRow[0].label.replace('产业', '专区'), leftTabItems)
            // 手动更新url上mapId值 和 form
            let pathname = ''
            if (activeTrackRow[0].label.replace('产业', '专区') === '生物医药专区') pathname = '/biomedicalArea'
            if (activeTrackRow[0].label.replace('产业', '专区') === '新能源专区') pathname = '/newEnergy'
            if (activeTrackRow[0].label.replace('产业', '专区') === '汽车专区') pathname = '/carArea'
            if (activeTrackRow[0].label.replace('产业', '专区') === '新材料专区') pathname = '/advancedMaterialArea'
            updateURLParams(pathname, activeTrackRow[1].value, activeTrackRow[1].map_id, activeTrackRow[1].label)

            removeItem('activeName')
          }
          setOpen(false)
        }}>
        <div className="flex items-center mb-10px">
          <p className="w-60px">赛道</p>
          <Cascader
            style={{ width: 'calc(100% - 60px)' }}
            showSearch={true}
            options={publishTrackList}
            onChange={(_value: any, row: any) => {
              setactiveTrackRow(row)
            }}
            placeholder="请选择赛道"
          />
        </div>
      </Modal>
    </div>
  )
}

export default BiomedicalArea
